package model;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * The Class that generate SDP Response Message to client
 */
public class SDP {

    private final static String CRLF = "\r\n";
    private String obStrInput, obServerAddress, obStrSDP;

    public SDP(String obStrInput, String obServerAddress) {
        this.obStrInput = obStrInput;
        this.obServerAddress = obServerAddress;
        setSDPMessage();
    }

    //Writing the SDP body
    private void setSDPMessage() {
        //TAKE CARE ABOUT THIS LATER
        this.obStrSDP = "v=0" + CRLF
                + "o=- " + getSessionID() + "IN IP4 " + obServerAddress + CRLF
                + "s=SJphone" + CRLF
                + "c=IN IP4 " + obServerAddress + CRLF
                + "t=0 0" + CRLF
                + "a=direction:active" + CRLF
                + "m=audio " + ((getRTPPort().substring(0, getRTPPort().length() - 1)) + (Integer.valueOf(getRTPPort().substring(getRTPPort().length() - 1)) + 1)) + " " + getAudio() + CRLF
                + "a=rtpmap:3 GSM/8000" + CRLF
                + "a=rtpmap:101 telephone-event/8000" + CRLF
                + "a=fmtp:101 0-11,16" + CRLF
                + "a=sendrecv";//maybe change to "a=sendonly sendrecv"*/
    }

    public String toString() {
        return obStrSDP;
    }

    //Need to create more readable code here, TAKE CARE ABOUT THIS LATER
    private String getAudio() {
        String strTemp = obStrInput.substring(obStrInput.indexOf("RTP/AVP"));
        strTemp = "RTP/AVP 3 101";
        return strTemp;
    }

    //Need to create more readable code here, TAKE CARE ABOUT THIS LATER
    private String getSessionID() {
        int fsp = obStrInput.indexOf("o=-");
        int nsp = obStrInput.indexOf(" ", fsp);
        fsp = obStrInput.indexOf(CRLF, nsp + 2);
        String obStrTemp = obStrInput.substring(nsp + 1, fsp);
        obStrTemp = obStrTemp.substring(0, obStrTemp.indexOf("IP") - 3);
        return obStrTemp;
    }

    private String getRTPAddress() {
        /* Obtenemos un Pattern con la expresi√≥n regular, y de √©l un Matcher, para extraer los trozos de inter√©s. */
        Pattern patron = Pattern.compile("SIP/2.0/UDP[ ](\\d+.\\d+.\\d+.\\d+)");
        Matcher matcher = patron.matcher(obStrInput);

        // Hace que Matcher busque los trozos.
        matcher.find();
        return matcher.group(1);
    }

    public String getRTPPort() {
        int fsp = obStrInput.indexOf("m=");
        int nsp = obStrInput.indexOf(" ", fsp);
        fsp = obStrInput.indexOf(" ", nsp + 2);
        return obStrInput.substring(nsp + 1, fsp);
    }
}//Class end

